const Service = require('egg').Service;

const myCookie = '111'
const TABLE = 'userList'

class HomeService extends Service {
  // async getTotal(uid) {
  //   const user = await this.ctx.db.query('select * from user where uid = ?', uid);
  //   return user;
  // }
  async getTotal(){
    const total = await this.app.mysql.get(TABLE, { myCookie });
    return total;
  }

  async getAllList(){
    const total = await this.app.mysql.select(TABLE);
    return total;
  }

  // isAddSame 表示是否是同一个cookie，如果是同一个，增加total，不用添加sameTotal
  async updateTotal(data, isAddSame = true){
    let { total, sameTotal } = data;
    const row = {
      myCookie,
      total: ++total,
      sameTotal: isAddSame ? sameTotal : ++sameTotal,    // any other fields u want to update
      // modifiedAt: this.app.mysql.literals.now, // `now()` on db server
    };

    // 主键是自定义的myCookie而不是id
    const options = {
      where: {
        myCookie
      }
    };
    const result = await this.app.mysql.update(TABLE, row, options ); // 更新 posts 表中的记录
    return result
  }

  async submitTable(){
    const total = await this.app.mysql.get(TABLE, { myCookie });
    let { passCount } = total;

    const row = {
      myCookie,
      passCount: ++passCount,    // any other fields u want to update
      // modifiedAt: this.app.mysql.literals.now, // `now()` on db server
    };

    const options = {
      where: {
        myCookie
      }
    }
    const result = await this.app.mysql.update(TABLE, row, options ); // 更新 posts 表中的记录
    return result
  }

  async passCount(){
    // const total = await this.app.mysql.get(TABLE, { myCookie });
  }

  async timeOb(data){
    const result = await this.app.mysql.insert(TABLE, data); // 在 post 表中，插入 title 为 Hello World 的记录
    return result
  }
}

module.exports = HomeService;